import { useAtomValue, useSetAtom } from "jotai";
import { NavLink, useParams } from "react-router";
import clsm from "@/lib/utils/clsm";
import LinkIcon from "@/assets/images/link.png?jsx";
import UnlinkIcon from "@/assets/images/unlink.png?jsx";
import useFetch from "@/lib/hooks/useFetch";
import { tokenAtom } from "@/store/user";
import { useDeviceContext } from "@/providers/DeviceProvider";
import useOnUpdated from "@/lib/hooks/useOnUpdated";
import useOnMounted from "@/lib/hooks/useOnMounted";
import Loading from "../Loading";
import { getDeviceStatusList } from "@/lib/api/deviceStatus";
import { setHeaderAtom } from "@/store/header";
import { useEffect } from "react";
import LongScrollText from "../LongScrollText";

export default function Aside() {
  const params = useParams<{ id?: string }>();
  const token = useAtomValue(tokenAtom);
  const {
    onDeviceChange,
    onDeviceListChange,
    loading: isLoadingDevice,
    onLoad: onDeviceLoaded,
    onReloadDeviceListHandlerChange,
  } = useDeviceContext();
  const setHeader = useSetAtom(setHeaderAtom);

  const {
    data: deviceList,
    isPending,
    isSuccess,
    refetch: loadDeviceList,
    cancel: cancelLoadDeviceList,
  } = useFetch({
    fetchFn: (signal) =>
      getDeviceStatusList(token, signal).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        return res.data;
      }),
    onSuccess(data) {
      onDeviceListChange(data);
    },
  });

  useOnMounted(() => {
    let timer: Timer;
    function start() {
      loadDeviceList();
      timer = setTimeout(start, 5000);
    }

    function cancel() {
      cancelLoadDeviceList();
      clearTimeout(timer);
    }

    function reload() {
      cancel();
      start();
    }

    onReloadDeviceListHandlerChange(reload);

    start();

    return () => {
      cancel();
      onReloadDeviceListHandlerChange();
    };
  });

  useOnUpdated(() => {
    if (!deviceList) {
      onDeviceChange();
      return;
    }
    const current = params.id ? parseInt(params.id) : undefined;
    const device = current
      ? deviceList.find((d) => d.deviceId === current)
      : undefined;
    onDeviceChange(device);
    isLoadingDevice && onDeviceLoaded();
    if (device) {
      const { mode, deviceStatus, deviceControl, status, conn } = device;
      setHeader({
        title:
          status === "0" || !conn
            ? ""
            : deviceControl
              ? "设备端控制中"
              : `${mode === "fix" ? "定值" : "程序"}${deviceStatus === "1" ? "待机" : deviceStatus === "2" ? "运行" : "保持"}中`,
        style: {
          color: deviceStatus !== "1" || deviceControl ? "#22C55E" : undefined,
        },
        pulse: deviceStatus === "2",
      });
    } else {
      setHeader({ title: "", style: {}, pulse: false });
    }
  }, [params.id, deviceList]);

  useEffect(() => {
    // 初次进入页面时滚动到所选设备
    document.getElementById(`dashboard-${params.id}`)?.scrollIntoView({
      behavior: "instant",
      block: "center",
    });
  }, []);

  return (
    <div className="w-[220px] flex-none text-sm dark:bg-[#131313]">
      <Loading loading={isPending || !isSuccess}>
        <ul className="max-h-full min-h-20 overflow-auto py-6">
          {(deviceList || []).map((item) => (
            <li key={item.deviceId} id={`dashboard-${item.deviceId}`}>
              <NavLink
                to={`/dashboard/${item.deviceId}`}
                className={({ isActive }) =>
                  clsm(
                    "relative flex cursor-pointer px-6 py-2.5 hover:bg-zinc-300 dark:hover:bg-[#494949]",
                    isActive &&
                      "bg-[#393939] before:absolute before:bottom-1 before:left-1 before:top-1 before:w-0.5 before:animate-height before:rounded before:bg-green-500 before:content-['']",
                  )
                }
              >
                {item.conn ? (
                  <LinkIcon className="mr-2 inline-block w-5 flex-none -rotate-90" />
                ) : (
                  <UnlinkIcon className="mr-2 inline-block w-5 flex-none -rotate-90" />
                )}
                <LongScrollText className="min-w-0 flex-auto">
                  {item.deviceName}
                </LongScrollText>
              </NavLink>
            </li>
          ))}
        </ul>
      </Loading>
    </div>
  );
}
